﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate.Cfg;
using FluentNHibernate.Cfg;
using System.Reflection;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;

namespace ConsoleApp.StructureMap
{
    public class NHibernateBootstrapper
    {
        private static Configuration _currentConfig;

        public static ISessionFactory SessionFactory { get; private set; }

        static NHibernateBootstrapper()
        {
            SessionFactory = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString("Server=127.0.0.1;Port=3306;Database=bbtest;Uid=root;Pwd=root;charset=utf8;"))
                .BuildSessionFactory();
        }

        private static FluentConfiguration ConfigureMappings()
        {
            return Fluently.Configure()
                .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                .ExposeConfiguration(c => _currentConfig = c);
        }

        public static ISessionFactory CreateSessionFactoryForTests()
        {
            return ConfigureMappings()
                .Database(SQLiteConfiguration.Standard.ShowSql().InMemory())
                .BuildSessionFactory();
        }

        public static ISessionFactory CreateSessionFactoryForProduction()
        {
            /// the config connectionstring name is dbpro
            return ConfigureMappings()
               .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("dbpro")))
               .BuildSessionFactory();
        }

        public static void CreateSchema(ISession session)
        {
            var exporter = new SchemaExport(_currentConfig);
            exporter.Execute(true, true, false, session.Connection, null);
        }


        public static void UpdateSchema()
        {
            var updater = new SchemaUpdate(_currentConfig);
            updater.Execute(true, true);
        }
    }
}